#include <rtthread.h>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>

static int _sendstr(const char *sip, const char *sport, const char *str)
{
    struct sockaddr_in saddr;
    int sock;
    ip_addr_t ia;
    int port;
    int ret;
    int len;

    port = atoi(sport);
    inet_aton(sip, &ia);

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        printf("create socket error\n");
        return -1;
    }

    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);
    saddr.sin_addr.s_addr = ia.addr;
    memset(&(saddr.sin_zero), 0, sizeof(saddr.sin_zero));

    if (connect(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr)) != 0)
    {
        /* 连接失败 */
        printf("Connect fail!\n");
        goto _out;
    }

    len = strlen(str);
    ret = send(sock, str, len, 0);
    if (ret != len)
    {
        printf("send fail (%d/%d)\n", ret, len);
    }

_out:
    closesocket(sock);

    return 0;
}

static int tcpsend(int argc, char *argv[])
{
    static char ip[16] = "192.168.31.8";
    static char port[8] = "8080";
    char *msg = "hello world";

    while (--argc > 0)
    {
        switch (argc)
        {
        case 3:
            msg = argv[argc];
            break;
        case 2:
            snprintf(port, sizeof(port), "%s", argv[argc]);
            break;
        case 1:
            snprintf(ip, sizeof(ip), "%s", argv[argc]);
            break;            
        }
    }

    _sendstr(ip, port, msg);

    return 0;
}
MSH_CMD_EXPORT(tcpsend, tcpsend IP PORT [STRING]);

static int gethost(int argc, char *argv[])
{
    struct hostent *host;
    char *url = "www.rt-thread.org";

    if (argc == 2)
        url = argv[1];

    host = gethostbyname(url);
    if (host)
    {
        struct in_addr ia;
        char ip[16] = {0};

        ia = *((struct in_addr *)host->h_addr);
        inet_ntoa_r(ia, ip, 16);

        printf("%s\n", ip);
    }

    return 0;
}
MSH_CMD_EXPORT(gethost, gethostbyname);
